from connect.models import QueryDatabase, RunSqlTask
from rest_framework import serializers


# 数据库查询信息序列化
class QueryDatabaseSerializers(serializers.ModelSerializer):

    class Meta:
        model = QueryDatabase
        fields = "__all__"


class RunSqlTaskSerializers(serializers.ModelSerializer):
    database = QueryDatabaseSerializers(read_only=False)

    class Meta:
        model = RunSqlTask
        fields = "__all__"

    def create(self, validated_data):
        database_data = validated_data.pop('database')
        database_instance, res = QueryDatabase.objects.get_or_create(d_address=database_data["d_address"],
                                                                     d_user=database_data["d_user"],
                                                                     d_port=database_data["d_port"],
                                                                     d_types=database_data["d_types"],
                                                                     s_address=database_data["s_address"],
                                                                     s_user=database_data["s_user"],
                                                                     s_port=database_data["s_port"],
                                                                     s_types=database_data["s_types"])
        validated_data["database"] = database_instance
        task_instance = RunSqlTask.objects.create(**validated_data)

        return task_instance

